import 'package:flutter/material.dart';
import 'package:qunaimedical/models/map_response.dart';
import 'package:qunaimedical/network/http.dart';
import 'package:qunaimedical/utils/sp_utils.dart';
import 'package:qunaimedical/values/urls.dart';

/// 签到界面
class AttendancePage extends StatefulWidget {
  static const String routeName = '/attendance';

  @override
  _AttendancePageState createState() => _AttendancePageState();
}

class _AttendancePageState extends State<AttendancePage> {
  /// 积分数量
  int _total = 0;

  /// 今日是否已签到
  bool _todaySign = false;

  List<String> _weeks = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];

  /// 存放日期和积分数
  Map<String, int> _dates = {};

  @override
  void initState() {
    super.initState();
    var date = DateTime.now().subtract(Duration(days: 3));
    for (int i = 0; i < 7; i++) {
      _dates[date.add(Duration(days: i)).toString().substring(0, 10)] = 0;
    }
    _fetchAttendenceList();
    _fetchStatistics();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text('签到')),
        body: Column(
          children: [
            Stack(
              alignment: Alignment.topCenter,
              children: [
                Image.asset(
                  'assets/images/bg_header_attendance.png',
                  width: MediaQuery.of(context).size.width,
                  height: 350,
                  fit: BoxFit.cover,
                ),
                Positioned(
                  top: 50,
                  child: Text(
                    '积分：$_total',
                    style: TextStyle(fontSize: 34, color: Colors.white),
                  ),
                ),
                Positioned(
                  top: 130,
                  child: Container(
                    width: 120,
                    height: 120,
                    decoration: BoxDecoration(
                      color: Color(0xffb0f1c5),
                      borderRadius: BorderRadius.all(
                        Radius.circular(60),
                      ),
                    ),
                    alignment: Alignment.center,
                    child: InkWell(
                      onTap: _todaySign ? null : _sign,
                      child: Container(
                        width: 90,
                        height: 90,
                        alignment: Alignment.center,
                        child: Text(
                          _todaySign ? '已签到' : '签到',
                          style: TextStyle(
                            color: Theme.of(context).primaryColor,
                            fontSize: 26,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        decoration: BoxDecoration(
                          color: _todaySign ? Colors.grey[300] : Colors.white,
                          borderRadius: BorderRadius.all(
                            Radius.circular(45),
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
            Container(
              transform: Matrix4.translationValues(0, -70, 0),
              child: Card(
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.all(Radius.circular(15.0))),
                child: Container(
                  height: 93,
                  width: MediaQuery.of(context).size.width - 40,
                  padding: EdgeInsets.symmetric(vertical: 10, horizontal: 5),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(15)),
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      // Container(
                      //   child: Text(
                      //     '已经连续签到2天',
                      //     style: TextStyle(
                      //         fontSize: 18, fontWeight: FontWeight.bold),
                      //   ),
                      //   margin: EdgeInsets.only(left: 20, top: 18),
                      // ),
                      Expanded(
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceAround,
                          children: List.generate(
                              7,
                              (index) => _buildOption(
                                  _dates.isEmpty
                                      ? DateTime.now()
                                      : DateTime.parse(
                                          _dates.keys.toList()[index]),
                                  _dates.values.toList()[index],
                                  index)),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            )
          ],
        ));
  }

  Container _buildOption(DateTime date, int value, int index) {
    num width = (MediaQuery.of(context).size.width - 40 - 8 * 10) / 7;
    return Container(
      width: width,
      child: Column(
        children: [
          Container(
            margin: EdgeInsets.only(top: 10),
            width: width - 10,
            height: width - 10,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.all(
                Radius.circular(20),
              ),
              color: Color(0xff12ca96),
            ),
            alignment: Alignment.center,
            child: index < 3
                ? Icon(
                    Icons.check_circle,
                    color: value == 0 ? Colors.grey : Colors.yellow,
                  )
                : (index == 3 && _todaySign)
                    ? Icon(
                        Icons.check_circle,
                        color: Colors.yellow,
                      )
                    : Text(
                        '+$value',
                        style: TextStyle(color: Colors.white),
                      ),
          ),
          Text(
            index == 3 ? '今天' : '${_weeks[date.weekday - 1]}',
            style: TextStyle(color: Colors.white),
          ),
        ],
      ),
      decoration: BoxDecoration(
        color: Theme.of(context).primaryColor,
        borderRadius: BorderRadius.all(Radius.circular(6)),
      ),
    );
  }

  /// 获取签到历史
  void _fetchAttendenceList() async {
    var data = await XHttp.postJson(Urls.SIGN_LIST, {
      "userId": SPUtils.getUser().id,
    });
    if (data != null && mounted) {
      Map<String, dynamic> response = Map<String, dynamic>.from(data);
      var rows = List.from(response['integralRecordList']);
      var now = DateTime.now();
      var today = now.toString().substring(0, 10);
      var yesterday =
          now.subtract(Duration(days: 1)).toString().substring(0, 10);
      // 昨天是否签到
      var yesterdaySign = false;
      for (int i = 0; i < rows.length; i++) {
        var row = rows[i];
        var day = row['createTime'].substring(0, 10);
        var integralVal = row['integralVal'];
        var integralType = row['integralType'];
        // 判断昨天是否签到
        if (day == yesterday && integralType == 'sign_in') {
          yesterdaySign = true;
        }
        // 如果有当天签到数据，修改标示
        if (day == today && integralType == 'sign_in') {
          _todaySign = true;
        }
        // 对签到数据字典进行赋值
        _dates.forEach((key, value) {
          if (key == day) {
            _dates[key] = integralVal;
          }
        });
      }
      // 如果昨天签到过，今天的签到积分值在昨天的基础上+1，没有的话，就是1
      if (yesterdaySign) {
        _dates[today] = _dates[yesterday] + 1;
      } else {
        _dates[today] = 1;
      }
      // 计算后三天的积分值
      for (int i = 0; i < 3; i++) {
        int value;
        if (_dates[today] < 7) {
          value = _dates[today] + 1 + i;
        } else {
          value = 7;
        }
        _dates[now.add(Duration(days: i + 1)).toString().substring(0, 10)] =
            value;
      }
      setState(() {});
    }
  }

  /// 签到
  void _sign() async {
    var data = await XHttp.postJson(Urls.SIGN_ADD, {
      "userId": SPUtils.getUser().id, // 当前登录人账户ID
      "userName": SPUtils.getUser().username, // 当前登录人手机号
    });
    if (data != null && mounted) {
      var response = MapResponse.fromJson(data);
      if (response.code == 200) {
        setState(() {
          _todaySign = true;
        });
        _fetchStatistics();
      }
    }
  }

  /// 获取统计信息
  void _fetchStatistics() async {
    var data =
        await XHttp.get('${Urls.STATISTICS}?doctorId=${SPUtils.getUser().id}');
    if (data != null && mounted) {
      setState(() {
        _total = data['doctorIntegral'];
      });
    }
  }
}
